// src/features/conversations/api/use-create-or-get-conversation.ts
import {useCallback, useMemo, useState} from "react";
import {v4 as uuidv4} from "uuid";
import {MARK_DATA_URL} from "@/lib/social/constants";

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    workspaceId: string
    memberId: string
    curMemberId: string
} | null

type ResponseType = {
    memberOneId: string
    memberTwoId: string
    workspaceId: string
    id: string
} | null


// client
export const useCreateOrGetConversation = () => {
    const [data, setData] = useState<ResponseType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        try {
            setData(null)
            setError(null)
            setStatus('pending')

            const cRes = await fetch(
                // `${MARK_DATA_URL}/conversations?workspaceId=${
                `/api/conversations?workspaceId=${
                    values?.workspaceId}&memberOneId=${values?.curMemberId
                }&memberTwoId=${values?.memberId}`
            )
            const cData = await cRes.json()
            // json-server 返回 数组
            if (cData && !(cData.length === 0)) {
                setStatus('success')
                setData(cData[0])
                options?.onSuccess?.(cData[0].id)
                return cData
            }

            // create workspace
            // const id = uuidv4()
            let conversation = {
                memberOneId: values?.curMemberId,
                memberTwoId: values?.memberId,
                workspaceId: values?.workspaceId,
                // id
            }
            // const res = await fetch(`${MARK_DATA_URL}/conversations`, {
            const res = await fetch(`/api/conversations`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    ...conversation
                }),
            })

            if (res.ok) {
                setStatus('success')
                const data = await res.json()
                setData(data)
                options?.onSuccess?.(data.id)
            }
            return conversation
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, isError, data
    }
}